package com.zzw.utils;

import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Shiro会话Redis工具类
 * 专门用于处理Shiro会话的Redis存储操作
 */
@Component
public class ShiroRedisUtil {
    
    @Autowired
    @Qualifier("shiroSessionRedisTemplate")
    private RedisTemplate<String, Session> shiroSessionRedisTemplate;
    
    /**
     * 设置Shiro会话
     *
     * @param key 键
     * @param session 会话
     * @param timeout 超时时间(秒)
     * @return 是否成功
     */
    public boolean setSession(String key, Session session, long timeout) {
        try {
            if (timeout > 0) {
                shiroSessionRedisTemplate.opsForValue().set(key, session, timeout, TimeUnit.SECONDS);
            } else {
                shiroSessionRedisTemplate.opsForValue().set(key, session);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 获取Shiro会话
     *
     * @param key 键
     * @return 会话
     */
    public Session getSession(String key) {
        return key == null ? null : shiroSessionRedisTemplate.opsForValue().get(key);
    }
    
    /**
     * 删除Shiro会话
     *
     * @param key 键
     */
    public void delSession(String key) {
        if (key != null) {
            shiroSessionRedisTemplate.delete(key);
        }
    }
    
    /**
     * 设置Shiro会话过期时间
     *
     * @param key 键
     * @param timeout 超时时间(秒)
     * @return 是否成功
     */
    public boolean expireSession(String key, long timeout) {
        try {
            if (timeout > 0) {
                shiroSessionRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
} 